package com.course.servlet;

import com.course.entity.Teacher;
import com.course.service.TeacherService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/laoshi_update_profile")
public class LaoshiUpdateProfileServlet extends HttpServlet {
    private final TeacherService teacherService = new TeacherService();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");

        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("teacher") == null) {
            response.sendRedirect(request.getContextPath() + "/laoshi_login.jsp");
            return;
        }

        Teacher currentTeacher = (Teacher) session.getAttribute("teacher");

        int id = currentTeacher.getId();
        String username = request.getParameter("username");
        String name = request.getParameter("name");
        String gender = request.getParameter("gender");
        String department = request.getParameter("department");
        String email = request.getParameter("email");
        String phone = request.getParameter("phone");
        String newPassword = request.getParameter("password"); // New password field
        String confirmPassword = request.getParameter("confirmPassword"); // Confirm password field

        Teacher updatedTeacher = new Teacher();
        updatedTeacher.setId(id);
        updatedTeacher.setUsername(username);
        updatedTeacher.setName(name);
        updatedTeacher.setGender(gender);
        updatedTeacher.setDepartment(department);
        updatedTeacher.setEmail(email);
        updatedTeacher.setPhone(phone);

        boolean updateSuccess = false;
        String errorMessage = null;

        try {
            // Update profile details (excluding password initially)
            teacherService.updateTeacher(updatedTeacher);
            updateSuccess = true; // Assume success for profile update for now

            // Handle password update if new password is provided
            if (newPassword != null && !newPassword.trim().isEmpty()) {
                if (newPassword.equals(confirmPassword)) {
                    boolean passwordUpdated = teacherService.updatePassword(id, newPassword);
                    if (!passwordUpdated) {
                        updateSuccess = false;
                        errorMessage = "密码修改失败。";
                    }
                } else {
                    updateSuccess = false;
                    errorMessage = "新密码和确认密码不匹配。";
                }
            }
        } catch (Exception e) {
            updateSuccess = false;
            errorMessage = "更新个人信息时发生错误: " + e.getMessage();
            e.printStackTrace();
        }

        if (updateSuccess) {
            session.setAttribute("successMessage", "个人信息更新成功！");
            // Re-fetch updated teacher info to refresh session attribute
            Teacher reloadedTeacher = teacherService.findById(id);
            if(reloadedTeacher != null) {
                session.setAttribute("teacher", reloadedTeacher);
            }
        } else {
            session.setAttribute("errorMessage", errorMessage != null ? errorMessage : "个人信息更新失败，请稍后重试。");
        }

        response.sendRedirect(request.getContextPath() + "/laoshi_personal_center");
    }
} 